<template>
  <div class="app-container bg-container" v-loading="loading">
    <div class="chart-select">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" :rules="rules">
        <el-form-item label="分类能耗" prop="energyType">
          <el-select v-model="queryParams.energyType" placeholder="请选择" @change="energyTypeChange">
            <el-option
              v-for="item in dict.type.energy_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="起止时间" prop="dateRange">
          <el-date-picker
            v-model="queryParams.dateRange"
            style="width: 300px"
            value-format="yyyy-MM-dd HH:mm:ss"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="['00:00:00', '23:59:59']"
            @change="getTimeRange"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="getTopologyList"
            >查询</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <el-empty v-if="this.value == 0" image="" style="height: 700px; width: 100%"></el-empty>
    <div v-else id="chart-sankey" style="height: 700px; width: 100%" />
  </div>
</template>

<script>
import * as echarts from "echarts";
import resize from "@/views/dashboard/mixins/resize";
import {
  topologyTreeSelect,
  listItemTopology,
} from "@/api/system/itemTopology";
import { getFlowData } from '@/api/system/energy'
import moment from 'moment/moment'

export default {
  mixins: [resize],
  dicts: ['energy_type'],
  props: {},
  data() {
    return {
      queryParams: {
        energyType: '0',
        dateRange: [],
      },
      energyType: [
        {
          value: 0,
          label: "电",
          unit: 'kW.h'
        },
        {
          value: 1,
          label: "水",
          unit: 't'
        },
      ],
      chart: null,
      treeData: {},
      rules: {
        dateRange: [
          { required: true, message: "请选择时间", trigger: "change" },
        ],
      },
      value:0,
      unit: 'kW.h',
      loading: true,
    };
  },
  mounted() {
    // 节点切换显示事件
    this.$nextTick(() => {
      if (this.chart) {
        this.chart.on('mousedown', (e) => {
          if (!this.chart._chartsViews || !this.chart._chartsViews[0]) return;
          const name = e.data.name;
          const curNode = this.chart._chartsViews[0]._data.tree._nodes.find(item => {
            return item.name === name;
          });
          if (!curNode) return;
          const depth = curNode.depth;
          const curIsExpand = curNode.isExpand;
          this.chart._chartsViews[0]._data.tree._nodes.forEach((item, index) => {
            if (item.depth === depth && item.name !== name && !curIsExpand) {
              item.isExpand = false;
            }
          });
        });
      }
    });
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    // 移除事件监听
    this.chart.off('mousedown');
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    defaultDate(){
      this.queryParams.dateRange = [moment().format("yyyy-MM-01 00:00:00"),moment().format("yyyy-MM-DD 23:59:59")]
    },
    initChart() {
      this.chart = echarts.init(document.getElementById("chart-sankey"));

      this.chart.setOption({
        tooltip: {
          trigger: "item",
          triggerOn: "mousemove",
          formatter: (params) => {
            if (params.data.value) {
              return `${params.data.name}: ${params.data.value}${this.unit}`;
            }
            return params.data.name;
          }
        },
        series: [
          {
            type: "tree",
            id: 0,
            name: 'tree1',
            data: [this.treeData],
            top: '10%',
            left: '10%',
            bottom: '20%',
            right: '10%',
            avoidLabelOverlap: true, // 防止标签重叠
            roam: true, // 移动+缩放
            scaleLimit: { // 缩放比例
              min: 0.7, // 最小的缩放值
              max: 4, // 最大的缩放值
            },
            layout: 'orthogonal', // 树图布局，orthogonal水平垂直方向
            orient: 'TB', // 树形方向 TB为上下结构 LR为左右结构
            symbol: 'circle', // 图形形状
            symbolSize: 14, // 状态大小
            edgeShape: 'polyline', // 线条类型
            initialTreeDepth: 2, // 初始展开的层级
            expandAndCollapse: true, // 子树折叠和展开的交互
            lineStyle: { // 结构线条样式
              width: 0.7,
              color: '#1E9FFF',
              type: 'solid'
            },
            label: { // 节点文本样式
              normal: {
                backgroundColor: '#81c5f7',
                position: 'bottom',
                verticalAlign: 'middle',
                align: 'center',
                borderColor: '#1E9FFF',
                color: '#fff',
                borderWidth: 1,
                borderRadius: 5,
                padding: 5,
                height: 40,
                width: 100,
                offset: [0, 30],
                fontSize: 13,
                shadowBlur: 10,
                shadowColor: 'rgba(0,0,0,0.25)',
                shadowOffsetX: 0,
                shadowOffsetY: 2,
                formatter: (params) => {
                  if (params.data.value) {
                    return `${params.data.name}\n${params.data.value}${this.unit}`;
                  }
                  return params.data.name;
                },
                overflow: 'break',
                lineOverflow: 'truncate'
              }
            },
            leaves: { // 叶子节点文本样式
              label: {
                backgroundColor: '#fff',
                color: '#333',
                position: 'bottom',
                rotate: 0,
                verticalAlign: 'middle',
                align: 'center',
                overflow: 'break',
                lineOverflow: 'truncate',
                borderColor: '#1E9FFF',
                borderWidth: 1,
                borderRadius: 5,
                padding: 5,
                height: 40,
                width: 100,
                offset: [0, 30],
                fontSize: 13,
                formatter: (params) => {
                  if (params.data.value) {
                    return `${params.data.name}\n${params.data.value}${this.unit}`;
                  }
                  return params.data.name;
                }
              }
            },
            animationDuration: 550,
            animationDurationUpdate: 750
          }
        ]
      });
      
      // 添加节点点击事件
      this.chart.on('mousedown', (e) => {
        if (!this.chart._chartsViews || !this.chart._chartsViews[0]) return;
        const name = e.data.name;
        const curNode = this.chart._chartsViews[0]._data.tree._nodes.find(item => {
          return item.name === name;
        });
        if (!curNode) return;
        const depth = curNode.depth;
        const curIsExpand = curNode.isExpand;
        this.chart._chartsViews[0]._data.tree._nodes.forEach((item, index) => {
          if (item.depth === depth && item.name !== name && !curIsExpand) {
            item.isExpand = false;
          }
        });
      });
    },
    getTimeRange() {
      console.log(this.queryParams.dateRange);
    },
    // getTopologyTree() {
    //   topologyTreeSelect().then((response) => {
    //     this.topologyOptions = response.data;
    //   });
    // },
    // 能耗类型切换
    energyTypeChange(value) {
      let item = this.energyType.find(t => t.value == this.queryParams.energyType)
      if(item) {
        this.unit = item.unit
      }

      this.getTopologyList()
    },
    getTopologyList() {
      this.$refs["queryForm"].validate((valid) => {
        if (valid) {
          let params = {
            startTime:this.queryParams.dateRange[0],
            endTime:this.queryParams.dateRange[1],
            energyType: this.queryParams.energyType,
            status: '0'
          }
          this.loading = true
          getFlowData(params).then((res) => {
            if (res.data == [] || res.data == null) {
              this.treeData = {};
              return;
            }

            // 构建树形结构
            this.treeData = this.buildTree(res.data);
            
            this.value = this.calculateTotalValue(res.data);
            
            if(this.value == 0){
              return
            }
            if (this.chart != null) {
              this.chart.dispose();
              this.chart = null;
            }
            this.$nextTick(() => {
              this.initChart();
            })
          }).finally(() => {
            this.loading = false
          });
        }
      });
    },
    
    // 构建树形结构
    buildTree(data) {
      if (!data || data.length === 0) return {};
      
      // 创建节点映射
      const nodeMap = {};
      data.forEach(item => {
        nodeMap[item.itemId] = {
          name: item.itemName,
          value: item.value,
          itemId: item.itemId,
          parentId: item.parentId,
          children: []
        };
      });
      
      // 找到根节点和构建父子关系
      let root = null;
      data.forEach(item => {
        const node = nodeMap[item.itemId];
        if (item.parentId && nodeMap[item.parentId]) {
          // 有父节点，添加到父节点的children中
          nodeMap[item.parentId].children.push(node);
        } else {
          // 没有父节点或父节点不存在，认为是根节点
          if (!root) {
            root = node;
          }
        }
      });
      
      // 清理空的children数组
      this.cleanEmptyChildren(root);
      
      return root || {};
    },
    
    // 清理空的children数组
    cleanEmptyChildren(node) {
      if (!node) return;
      if (node.children && node.children.length === 0) {
        delete node.children;
      } else if (node.children) {
        node.children.forEach(child => this.cleanEmptyChildren(child));
      }
    },
    
    // 计算总值
    calculateTotalValue(data) {
      let total = 0;
      data.forEach(item => {
        if (item.value != null) {
          total += parseInt(item.value);
        }
      });
      return total;
    },
  },
  created() {
    this.defaultDate();
    // this.getTopologyTree()
    this.$nextTick(() => {
      this.getTopologyList()
    })
  },
};
</script>
<style lang="scss" scoped>
.app-container {
  min-height: calc(100vh - 84px);
  .chart-select {
    margin-top: 12px;
  }
}
</style>
